<template>
  <div>
    <div style="display: flex; flex-direction: row;">
      <div style="width: 320px;">
        <Input
          v-for="condition in BookSource.BSSearchOptions.conditions"
          :key="condition.name"
          :placeholder="condition.UIName"
          v-model="BSSearchOptions[condition.name]"
        />
      </div>
      <div style="margin-left: 20px;">
        <Button @click="handleSearch">搜索</Button>
      </div>
    </div>
    <Divider />
    <Table
      v-show="books.length > 0"
      border
      stripe
      :loading="loading"
      :columns="netBooks"
      :data="books"
    >
      <template style="width: 150px;" slot-scope="{ row }" slot="action">
        <div>
          <Button style="margin-left: 20px;" @click="handleSave(row)">存入书架</Button>
        </div>
      </template>
    </Table>
  </div>
</template>

<script>
import { searchBook, saveBook } from '../api/netBook'
import { addBookToMyBookShelf } from '../api/bookShelf'

export default {
  name: 'NetBook',

  props: {
    BookSource: {
      type: Object,
      required: true
    }
  },

  data () {
    return {
      BSSearchOptions: {},
      books: [],
      netBooks: [
        {
          title: 'Name',
          key: 'bname',
          width: 'auto'
        },
        {
          title: 'Author',
          key: 'author',
          width: 200
        },
        {
          title: 'Action',
          key: 'action',
          slot: 'action',
          width: 240
        }
      ],
      loading: false
    }
  },

  methods: {
    async handleSearch () {
      const searchOptions = {
        BSIndex: this.BookSource.BSIndex,
        BSName: this.BookSource.BSName,
        ...this.BSSearchOptions
      }
      const res = await searchBook(searchOptions)
      this.books = res.data
    },
    async handleSave (row) {
      saveBook({
        BSIndex: this.BookSource.BSIndex,
        BSName: this.BookSource.BSName,
        book: row
      }).then(res => {
        this.$Notice.success({
          title: '书籍存入系统成功!',
          desc: '正在保存书籍到书架...',
          duration: 5
        })
        addBookToMyBookShelf(res.data._id).then(res => {
          this.$Notice.success({
            title: '保存成功!',
            desc: `${res.data.bookName} 保存成功!`,
            duration: 5
          })
        }).catch(err => {
          this.$Notice.error({
            title: '保存失败,请去本地搜书中手动保存',
            desc: err.response.data.message,
            duration: 5
          })
        })
      }).catch(err => {
        this.$Notice.error({
          title: '书籍存入系统失败',
          desc: err.response.data.message,
          duration: 5
        })
      })
    }
  }
}
</script>

<style scoped>
</style>
